package com.blockmeta.bbs.overallserviceapplication.search.fragment;

import android.content.Context;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.pojo.SearchCoinsPOJO;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.search.adapter.CoinsSearchAdapter1;
import com.blockmeta.bbs.overallserviceapplication.search.adapter.CoinsSearchAdapter2;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by author on 2018/1/10.
 */
@Route(path = RouterPath.SEARCH_COINS_RESULT_FRAGMENT)
public class SearchCoinsResultFragment extends BaseFragment implements TabLayout.OnTabSelectedListener{

    private Context mContext;
    private View v;
    private String search;
    private String mWord;
    private RecyclerView recy1;
    private RecyclerView recy2;
    private SearchCoinsPOJO searchCoinsPOJO;
    private TabLayout mTabLayout;
    private LinkedHashMap<String,String> tabTitles;
    private CoinsSearchAdapter2 mCoinsAdapter;

    @Autowired(name = Constant.ZERO)
    public String mKey;
    @Autowired(name = Constant.ONE)
    public String mValue;
    @Autowired(name = Constant.THREE)
    public boolean mIM;
    public static SearchCoinsResultFragment newInstance(String key1, String value1) {
        SearchCoinsResultFragment fragment = new SearchCoinsResultFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.ZERO, key1);
        bundle.putString(Constant.ONE, value1);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        mContext = getActivity();
        v = LayoutInflater.from(mContext).inflate(R.layout.item_search_result_type1, null);
        return v;
    }

    @Override
    public void initView() {
        recy1 = v.findViewById(R.id.search_coin_recy1);
        recy2 = v.findViewById(R.id.search_coin_recy2);

        recy1.setHasFixedSize(false);
        recy2.setHasFixedSize(false);
        mTabLayout = v.findViewById(R.id.tab_coin_kinds);
        initData();
    }

    private void initData() {
        String url = NetConstant.COINS_SEARCH_RESULT;

        OKHttpGetReq okHttpGetReq = new OKHttpGetReq(mContext, url);
        HashMap<String, String> map = new HashMap<>();
        map.put("key", getArguments().getString(Constant.ZERO));
        map.put("word",getArguments().getString(Constant.ONE));
        okHttpGetReq.getDataWithParam(new Callback() {
            @Override
            public void onError(String resp) {
            }

            @Override
            public void onResponse(String resp, int id) {
                processData(resp);
            }
        }, map);
    }

    private void processData(String resp) {
        searchCoinsPOJO = GsonUtil.buildGson().fromJson(resp, SearchCoinsPOJO.class);
        initRecy1();
        initRecy2();
        initTab();
    }

    /**
     * 创建
     */
    private void initTab() {
        tabTitles = new LinkedHashMap<>();
        tabTitles.put("全部",null);
        if(searchCoinsPOJO.getCoins() != null) {
            for (SearchCoinsPOJO.CoinsBean coinsBean : searchCoinsPOJO.getCoins()) {
                tabTitles.put(coinsBean.getName(), coinsBean.getExchangeLogo());
            }
        }
        for (Map.Entry<String, String> stringIntegerEntry : tabTitles.entrySet()) {
            TabLayout.Tab tab=mTabLayout.newTab();
            View view= LayoutInflater.from(mContext).inflate(R.layout.tab_custom,null);
            ImageView imageView= view.findViewById(R.id.tab_icon);
            if (TextUtils.isEmpty(stringIntegerEntry.getValue())){
                imageView.setVisibility(View.GONE);
            }else {
                Picasso.with(mContext).load(stringIntegerEntry.getValue()).into(imageView);
            }
            TextView textView= view.findViewById(R.id.tab_text);
            textView.setText(stringIntegerEntry.getKey());
            tab.setCustomView(view);
            mTabLayout.addTab(tab);
        }
        mTabLayout.addOnTabSelectedListener(this);
    }


    /**
     * Ranking数据
     */
    private void initRecy1() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy1.setLayoutManager(manager);
        CoinsSearchAdapter1 rankingAdapter = new CoinsSearchAdapter1(R.layout.item_coins_list_for_search_result, searchCoinsPOJO.getRanking());
        View header = LayoutInflater.from(mContext).inflate(R.layout.item_search_result_header, null);
        TextView tv = (TextView) header.findViewById(R.id.search_result_header);
        tv.setText("市值数据");

        recy1.setAdapter(rankingAdapter);
    }

    /**
     * Coins数据
     */
    private void initRecy2() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy2.setLayoutManager(manager);
        mCoinsAdapter = new CoinsSearchAdapter2(R.layout.item_coins_list_for_search_result, searchCoinsPOJO.getCoins());
        recy2.setAdapter(mCoinsAdapter);
        mCoinsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<SearchCoinsPOJO.CoinsBean> coinsBeans = mCoinsAdapter.getData();
                String exchange = coinsBeans.get(position).getExchange() + "";
                String pair = coinsBeans.get(position).getCoin() + "_" +
                        coinsBeans.get(position).getCurrency();
                saveData(pair, exchange);
                startToDetailTicker(mContext, pair, exchange);
            }
        });
        View empty ;
        if (getArguments()!=null&&getArguments().getBoolean(Constant.THREE)){
            empty = LayoutInflater.from(mContext).inflate(R.layout.empty_search_for_im, null);
        }else {
            empty = LayoutInflater.from(mContext).inflate(R.layout.empty_search, null);
        }
        if (searchCoinsPOJO==null||searchCoinsPOJO.getRanking()==null||searchCoinsPOJO.getRanking().size() == 0) {
            mTabLayout.setVisibility(View.GONE);
            mCoinsAdapter.setEmptyView(empty);
        }else {
            mTabLayout.setVisibility(View.VISIBLE);
        }
    }

    private void saveData(String pair, String exchange) {
        SharedPreferenceUtil.putString(mContext, Constant.U_EXCHANGE, exchange);
        SharedPreferenceUtil.putString(mContext, Constant.U_PAIR, pair);
    }

    /**
     * @param tab tab监听
     */
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (tab.getPosition() == 0){
            recy1.setVisibility(View.VISIBLE);
            mCoinsAdapter.setNewData(searchCoinsPOJO.getCoins());
        }else {
            TextView textView=tab.getCustomView().findViewById(R.id.tab_text);
            String condition = textView.getText().toString();
            mCoinsAdapter.setNewData(filter(searchCoinsPOJO.getCoins(),condition));
            recy1.setVisibility(View.GONE);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    /**
     * 根据交易所名字过滤出交易所的相关数据
     * @param totalList 总列表
     * @param condition 需要的交易所名字
     * @return 返回同一交易所下的所有交易对
     */
    public List<SearchCoinsPOJO.CoinsBean> filter(List<SearchCoinsPOJO.CoinsBean> totalList, String condition){
        List<SearchCoinsPOJO.CoinsBean> list = new ArrayList<>();
        for (SearchCoinsPOJO.CoinsBean coinsBean : totalList) {
            if (condition.equals(coinsBean.getName())){
                list.add(coinsBean);
            }
        }
        return list;
    }
}
